#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QDir>
#include <QDebug>
#include <QMenu>

#include "athlete/createnewathlete.h"
#include "storage/sql/sqllite.h"
#include "settingsdialog.h"
#include "athlete/genderdelegate.h"
#include "competition/competitionmanager.h"


/*!
    \fn MainWindow
    Constructor of the MainWindow
  */
MainWindow::MainWindow(SystemController *controller, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //Sets the Vars
    ui->setupUi(this);
    this->systemController = controller;
    this->showMaximized();

    //Creates the needed Model
    //QSqlDatabase db = QSqlDatabase::database("sqlDb", false);
    QSqlDatabase db = QSqlDatabase::cloneDatabase(QSqlDatabase::database("sqlDb", false), "sqlDbMainWindow");
    db.setDatabaseName(this->systemController->getDatabasePath());
    db.open();
    this->model = new AthleteModel(this->systemController ,this, db);
    this->model->setTable("athlete");
    this->model->setEditStrategy(QSqlTableModel::OnFieldChange);

    this->model->setHeaderData(AthleteModel::NAME_COLUMN, Qt::Horizontal, tr("Name"));
    this->model->setHeaderData(AthleteModel::FIRST_NAME_COLUMN, Qt::Horizontal, tr("First Name"));
    this->model->setHeaderData(AthleteModel::BIRTH_DATE_COLUMN, Qt::Horizontal, tr("Birth Date"));
    this->model->setHeaderData(AthleteModel::GENDER_COLUMN, Qt::Horizontal, tr("Gender"));
    this->model->setHeaderData(AthleteModel::PHONE_COLUMN, Qt::Horizontal, tr("Phone"));
    this->model->setHeaderData(AthleteModel::MOBILE_COLUMN, Qt::Horizontal, tr("Mobile"));
    this->model->setHeaderData(AthleteModel::MAIL_COLUMN, Qt::Horizontal, tr("Mail"));
    this->model->setHeaderData(AthleteModel::CID_COLUMN, Qt::Horizontal, tr("Competetive Id expire"));

    //Set the Model + Settings for TableView
    ui->tableView->setModel(this->model);
    ui->tableView->hideColumn(AthleteModel::ID_COLUMN);

    //Set the Delegates for the TableView
    this->gndDelegate = new GenderDelegate(this);
    ui->tableView->setItemDelegateForColumn(AthleteModel::GENDER_COLUMN, this->gndDelegate);

    //Connect the needed Slots
    connect(this->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(refreshView()));
    connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showRightClickMenu(QPoint)));

    //Fill the View
    refreshView();
}


/*!
    \fn ~MainWindow
    Destructor of the MainWindow
  */
MainWindow::~MainWindow()
{
    delete this->gndDelegate;
    delete this->model;
    delete ui;
    delete this->systemController;
}



//////////
//Slots//
////////

/*!
    \fn refreshView
    Function to refresh the View
  */
void MainWindow::refreshView()
{
    if (!this->model->select())
    {
        this->systemController->showErrorDialog(this, tr("Error while loading data"), tr("While loading the data an error occoured"),
                                                this->model->lastError().text());
    }
    ui->tableView->resizeColumnsToContents();
    this->model->sort(AthleteModel::BIRTH_DATE_COLUMN, Qt::DescendingOrder);
}

/*!
    \fn refreshView
    Function to add an Athlete
  */
void MainWindow::on_actionSportler_hinzuf_gen_triggered()
{
    CreateNewAthlete newAthleteDialog(this->systemController, this);

    if (QDialog::Accepted == newAthleteDialog.exec())
    {
        //If Dialog result ok, create the SqlStatement
        QString stmt;
        stmt = "INSERT INTO athlete(\"aId\", \"name\", \"firstName\", \"birthDate\", \"gender\", \"phone\", \"mobile\", \"mail\", \"competitiveIdExp\") VALUES(NULL,\"" +
                newAthleteDialog.getName() +
                "\", \"" + newAthleteDialog.getFirstName() +
                "\", \"" + newAthleteDialog.getBirtDate().toString("yyyy-MM-dd") +
                "\", \"" + newAthleteDialog.getGender() +
                "\", \"" + newAthleteDialog.getPhone() +
                "\", \"" + newAthleteDialog.getMobile() +
                "\", \"" + newAthleteDialog.getMail() +
                "\", \"" + newAthleteDialog.getCIdExp().toString("yyyy-MM-dd") +
                "\");";


        //Execute the SqlStatement
        SqlLite db;
        if (!db.connect(this->systemController->getDatabasePath()))
            this->systemController->showErrorDialog(this, tr("Error while adding the Athlete"), tr("While adding the Athlete an error occoured"),
                                                    db.getLasterErrorMessage());
        else
        {
            if (!db.executeCommand(stmt))
                this->systemController->showErrorDialog(this, tr("Error while adding the Athlete"), tr("While adding the Athlete an error occoured"),
                                                        db.getLasterErrorMessage());
            else
                refreshView();
        }
        db.disconnect();


    }
    newAthleteDialog.close();
}

/*!
    \fn on_actionSettings_triggered
    Function to open the settings dialog
  */
void MainWindow::on_actionSettings_triggered()
{
    SettingsDialog dlg(this->systemController, this);
    if (QDialog::Accepted == dlg.exec())
    {
        systemController->getSettings()->setValue("settings/language", dlg.getLanguage());
    }
    dlg.close();
}

/*!
  \fn on_actionSportler_entfernen_triggered
  Function which is called when a athlete should be removed
  */
void MainWindow::on_actionSportler_entfernen_triggered()
{
    //Get the affected column
    int row = ui->tableView->selectionModel()->currentIndex().row();
    if (row != -1)
    {
        QString questionString = tr("Are you sure to delete athlete ");
        questionString.append(this->model->data(this->model->index(row, AthleteModel::NAME_COLUMN)).toString());
        questionString.append(", ");
        questionString.append(this->model->data(this->model->index(row, AthleteModel::FIRST_NAME_COLUMN)).toString());
        questionString.append("?");

        if (QMessageBox::question(this, tr("Sure to delete the Athlete"), questionString,
                              QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
        {
            QString id = this->model->data(this->model->index(row, AthleteModel::ID_COLUMN)).toString();
            //Execute the SqlStatement
            QString stmt = "DELETE FROM athlete WHERE aId=" +id;
            SqlLite db;
            if (!db.connect(this->systemController->getDatabasePath()))
            {
                this->systemController->showErrorDialog(this, tr("Error while removing the Athlete"), tr("While removing the Athlete an error occoured"),
                                                        db.getLasterErrorMessage());
            }
            else
            {
                if (!db.executeCommand(stmt))
                {
                    this->systemController->showErrorDialog(this, tr("Error while removing the Athlete"), tr("While removing the Athlete an error occoured"),
                                                            db.getLasterErrorMessage());
                }
                else
                    refreshView();
            }
            db.disconnect();
        }
    }
}




/*!
  \fn showRightClickMenu
  Functions to show a right click Menu
  */
void MainWindow::showRightClickMenu(const QPoint & pos )
{
    QMenu menu;
    //qDebug() << "Spalte: " <<ui->tableView->selectionModel()->currentIndex().column() << "Zeile: " <<ui->tableView->selectionModel()->currentIndex().row();
    menu.addAction(QIcon(":/athlete/16/user-new-2.png"), tr("Add Athlete"), this, SLOT(on_actionSportler_hinzuf_gen_triggered()));
    menu.addAction(QIcon(":/athlete/16/user-delete.png"), tr("Remove Athlete"), this, SLOT(on_actionSportler_entfernen_triggered()));
    menu.exec(QCursor::pos());
}


void MainWindow::on_toolButton_clicked()
{
    CompetitionManager compManager(this->systemController, this);
    compManager.setWindowFlags(Qt::Window|Qt::WindowSystemMenuHint| Qt::WindowTitleHint|Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint);
    compManager.exec();
}
